using dnAnalytics.LinearAlgebra;
using dnAnalytics.LinearAlgebra.Solvers;
using dnAnalytics.LinearAlgebra.Solvers.Preconditioners;

namespace dnAnalytics.Examples.LinearAlgebra.Solvers
{
    /// <summary>
    /// Provides an example of the creation of the BiCGStab iterative solver
    /// </summary>
    public sealed class BicgstabSolverConstructor
    {
        /// <summary>
        /// The main method that runs the BiCGStab iterative solver.
        /// </summary>
        public void CreateSolver()
        {
            // Create a sparse matrix. For now the size will be 10 x 10 elements
            // Normally you would want to fill the matrix too but for the example we'll 
            // forget about that.
            Matrix coefficientMatrix = MatrixBuilder.CreateMatrix(10, MatrixType.Sparse);

            // Create the preconditioner
            // Here we'll use the simple diagonal preconditioner.
            // We need a link to the matrix so the pre-conditioner can do it's work.
            IPreconditioner preconditioner = new DiagonalPreconditioner(coefficientMatrix);

            // Create a new convergence monitor. This checks for convergence of the results of the
            // iterative matrix solver.
            // In this case:
            // We perform a maximum of 5000 iterations.
            // We will stop when the residual drops below 1e-14
            // And use the infinity norm as the appropriate norm for the convergence measurement.
            ConvergenceMonitor monitor = new ConvergenceMonitor(5000,
                                                                1e-14,
                                                                coefficientMatrix.InfinityNorm());

            // Create the solver
            BiConjugateGradientStabilizedSolver solver =
                new BiConjugateGradientStabilizedSolver(coefficientMatrix, preconditioner, monitor);
        }
    }
}